---
sidebar_position: 3
title: React hooks - useFetch
sidebar_label: useFetch
---

# useFetch

[Read the API Reference »](/api/react/Hooks/useFetch.mdx)

The `useFetch` hook is your main tool for **fetching and reading data** from a server in React components. It integrates
seamlessly with Hyper Fetch's core systems, such as the [`Dispatcher`](/docs/core/dispatcher) and
[`Cache`](/docs/core/cache), to deliver a robust, reactive, and efficient data-fetching experience.

:::tip Purpose

1. **Declarative data fetching**: Provide a `Request` and let the hook manage the process.
2. **Automatic state management**: Handles `loading`, `error`, and `data` states for you.
3. **Built-in reactivity**: Automatically re-fetches data when dependencies change.
4. **Lifecycle callbacks**: Easily run side effects on success, error, or completion.
5. **Deep cache integration**: Uses a central cache to avoid redundant requests and boost performance.

:::

> To send data to the server (such as creating, updating, or deleting resources), use the
> [`useSubmit`](/react/04-hooks/use-submit.mdx) hook instead.

---

## Quick Start

To use `useFetch`, provide a prepared [`Request`](/docs/core/request) instance. The hook returns the current state of
that request, including the fetched `data`, `loading` status, and any `error` that may have occurred.

```tsx live title="Fetching a list of users" size=md
import { useFetch } from "@hyper-fetch/react";
import { getUsers } from "./api/users";

function App() {
  const { data, loading, error } = useFetch(getUsers);

  if (error) {
    return (
      <Alert severity="error">
        <span>{error.message}</span>
      </Alert>
    );
  }

  return (
    <div>
      <h3 className="mb-4">Users:</h3>
      <div className="flex flex-wrap gap-2">
        <Table data={data} loading={loading} />
      </div>
    </div>
  );
}
```

<LinkCard
  type="docs"
  title="Request"
  description="Learn more about creating and configuring requests."
  to="/docs/core/request"
/>

---

## Dependencies

`useFetch` can automatically re-fetch data when its request or dependency array changes. Pass a dependency array in the
options object (the second argument). When any value in the array changes, the hook triggers a new request.

This is especially useful for fetching data based on props, state, or other dynamic values.

```tsx live title="Re-fetching on dependency change" size=md
import { useFetch } from "@hyper-fetch/react";
import { getUsers } from "./api/users";

function App() {
  const [search, setSearch] = useState("");
  const { data, loading, error } = useFetch(getUsers.setQueryParams({ search }), {
    // This will debounce the request for 400ms
    bounce: true,
    bounceTime: 400,
    bounceType: "debounce",
  });

  return (
    <div>
      <TextField label="Search" placeholder="Type to search by name" onChange={(e) => setSearch(e.target.value)} />
      {data && (
        <div>
          <h3 className="mb-4">Users:</h3>
          <div className="flex flex-wrap gap-2">
            <Table data={data} loading={loading} />
          </div>
        </div>
      )}
    </div>
  );
}
```

---

## Event Handlers

To handle side effects such as notifications, logging, or triggering other actions, `useFetch` provides a set of event
handler hooks. This keeps your component's rendering logic clean and separates side effects from state management.

1. `onSuccess`: Fires when the request completes successfully. The callback receives the success `response`.
2. `onError`: Fires when the request results in an error. The callback receives the `error` object.
3. `onFinished`: Fires when the request finishes, regardless of the outcome.

```tsx live title="Using Event Handlers" size=md
import { useFetch } from "@hyper-fetch/react";
import { getUsers } from "./api/users";

const UsersListPage = () => {
  const { data, loading, onSuccess, onError, onFinished } = useFetch(getUsers);

  onSuccess(({ response }) => {
    toast({
      title: "Success",
      message: "Users fetched successfully",
      type: "success",
    });
  });

  onError(({ error }) => {
    toast({
      title: "Error",
      message: error.message,
      type: "error",
    });
  });

  onFinished(() => {
    toast({
      title: "Finished",
      message: "Finished request",
      type: "default",
    });
  });

  return (
    <div>
      <h3 className="mb-4">Users:</h3>
      <div className="flex flex-wrap gap-2">
        <Table data={data} loading={loading} />
      </div>
    </div>
  );
};
```

---

## Download and Upload Progress

`useFetch` provides two event handlers for tracking download and upload progress:

- `onDownloadProgress`: Fires when the request is downloading data.
- `onUploadProgress`: Fires when the request is uploading data.

Both handlers receive give you access to a `ProgressType` object containing crucial information about the request's
progress.

(@import core ProgressType type=returns)

:::success Rich progress tracking

We are providing advanced progress tracking for both download and upload - with ETA, size left, total size, loaded size,
and more.

:::

```tsx live title="Using Download and Upload Progress" size=md
import { useFetch } from "@hyper-fetch/react";
import { postFile } from "./api/files";

const UsersListPage = () => {
  const { data, onDownloadProgress, onUploadProgress } = useFetch(postFile);
  const { requests } = useQueue(postFile);
  console.log(requests);

  onDownloadProgress((progress) => {
    // Do something with the progress data
  });

  onUploadProgress((progress) => {
    // Do something with the progress data
  });

  return (
    <div>
      <h3 className="mb-4">Request Progress</h3>
      {/* Custom component to visualize progress */}
      {/* Uses 'useQueue' under the hood */}
      <RequestsLifecycle request={postFile} dispatcherType="fetch" />
    </div>
  );
};
```

---

## Options

Customize the behavior of `useFetch` by passing an options object as the second argument.

```tsx
const { ... } = useFetch(request, {
  disabled: false,
  dependencies: [],
  revalidate: true,
  // ... and more
});
```

Below is a full list of available options.

(@import react UseFetchOptionsType type=returns)

<LinkCard
  type="api"
  title="UseFetchOptionsType API Reference"
  description="Learn more about the useFetch hook."
  to="/docs/api/react/Types/UseFetchOptionsType"
/>

---

## State and Methods

`useFetch` returns an object containing the request's state, helper methods, and event handlers.

```tsx
const {
  data,
  error,
  loading,
  status,
  refetch,
  onSuccess,
  // ... and more
} = useFetch(request);
```

Below is a full list of returned values.

(@import react UseFetchReturnType type=returns)

<LinkCard
  type="api"
  title="useFetch API Reference"
  description="Learn more about the useFetch hook."
  to="/docs/api/react/Hooks/useFetch"
/>

---

## See More

<LinkCard
  type="guides"
  title="Fetching data"
  description="Learn more about fetching data with useFetch."
  to="/docs/guides/react/basics/fetching"
/>

<LinkCard
  type="docs"
  title="useSubmit"
  description="Learn more about the useSubmit hook."
  to="/docs/react/hooks/use-submit"
/>

<LinkCard
  type="docs"
  title="useCache"
  description="Learn more about the useCache hook."
  to="/docs/react/hooks/use-cache"
/>
